/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package fr.loof.fonzie.gigai;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.EntityNotFoundException;
import javax.persistence.FlushModeType;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.persistence.TemporalType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * @author <a href="nicolas@apache.org">Nicolas De Loof</a>
 *
 */
@Deprecated
public class QueryGigai
    implements Query
{
    private int firstResult = 0;

    private int maxResults = 1000;

    private String query;

    private EntityManagerGigai gigai;

    /**
     * @param query
     * @param gigai TODO
     */
    public QueryGigai( String query, EntityManagerGigai gigai )
    {
        super();
        query = StringUtils.replace( query, "\t", " " );
        query = StringUtils.replace( query, "\r", "" );
        query = StringUtils.replace( query, "\n", "" );
        query = StringUtils.replace( query, "  ", "" );
        query = StringUtils.replace( query, "  ", "" );
        this.query = query;
        this.gigai = gigai;
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#executeUpdate()
     */
    public int executeUpdate()
    {
        return gigai.findMatchingEntities( query ).size();
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#getResultList()
     */
    public List getResultList()
    {
        List result = gigai.findMatchingEntities( query );
        if ( firstResult > result.size() )
        {
            return Collections.EMPTY_LIST;
        }
        int to = Math.min( result.size(), firstResult + maxResults );
        return result.subList( firstResult, to );
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#getSingleResult()
     */
    public Object getSingleResult()
    {
        List result = getResultList();
        if ( result.size() > 1 )
        {
            throw new NonUniqueResultException();
        }
        if ( result.size() == 0 )
        {
            throw new EntityNotFoundException();
        }
        return result.get( 0 );
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setFirstResult(int)
     */
    public Query setFirstResult( int startPosition )
    {
        this.firstResult = firstResult;
        return this;
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setFlushMode(javax.persistence.FlushModeType)
     */
    public Query setFlushMode( FlushModeType flushMode )
    {
        return this;
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setHint(java.lang.String, java.lang.Object)
     */
    public Query setHint( String hintName, Object value )
    {
        return this;
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setMaxResults(int)
     */
    public Query setMaxResults( int maxResult )
    {
        this.maxResults = maxResults;
        return this;
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setParameter(java.lang.String, java.lang.Object)
     */
    public Query setParameter( String name, Object value )
    {
        if (AnnotationUtils.findAnnotation( value.getClass(), Entity.class ) != null)
        {
            value = gigai.getId( value );
        }
        query = StringUtils.replace( query, ":" + name, value.toString() );
        return this;
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setParameter(int, java.lang.Object)
     */
    public Query setParameter( int position, Object value )
    {
        throw new UnsupportedOperationException( "maybe some day..." );
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setParameter(java.lang.String, java.util.Date, javax.persistence.TemporalType)
     */
    public Query setParameter( String name, Date value, TemporalType temporalType )
    {
        return setParameter( name, toString( value, temporalType ) );
    }

    private String toString( Date value, TemporalType temporalType )
    {
        String date;
        switch ( temporalType )
        {
            case DATE:
                date = FastDateFormat.getDateInstance( FastDateFormat.SHORT ).format( value );
                break;

            default:
                date = FastDateFormat.getDateTimeInstance( FastDateFormat.SHORT, FastDateFormat.SHORT ).format( value );
                break;
        }
        return date;
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setParameter(java.lang.String, java.util.Calendar, javax.persistence.TemporalType)
     */
    public Query setParameter( String name, Calendar value, TemporalType temporalType )
    {
        return setParameter( name, value.getTime(), temporalType );
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setParameter(int, java.util.Date, javax.persistence.TemporalType)
     */
    public Query setParameter( int position, Date value, TemporalType temporalType )
    {
        return setParameter( position, toString( value, temporalType ) );
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.persistence.Query#setParameter(int, java.util.Calendar, javax.persistence.TemporalType)
     */
    public Query setParameter( int position, Calendar value, TemporalType temporalType )
    {
        return setParameter( position, value.getTime(), temporalType );
    }

}
